//
//  AppStoreController.m
//  gdemm
//
//  Created by 乔明超 on 2017/8/8.
//  Copyright © 2017年 Goldencis. All rights reserved.
//

#import "AppStoreController.h"
#import "CollectionViewCell.h"
#import "AppDetailController.h"
#import "Masonry.h"
#import "Constants.h"
#import "Utils.h"
#import "HttpUtil.h"
#import "ApiSupport.h"
#import "AppInfoModel.h"
#import "getAppInfo.h"
#import "LSApplicationProxy.h"
#import "LSApplicationWorkspace.h"
#import <dlfcn.h>
#import "SVProgressHUD.h"
#import "PackageInfo.h"
#import "MBProgressHUD.h"
@interface AppStoreController ()<UITextFieldDelegate,ASIHTTPRequestDelegate>
@property(nonatomic,strong)NSArray * insideAppinfoArray;
@property(nonatomic,strong)NSArray * outsideAppinfoArray;
@property(nonatomic,strong)NSMutableArray * searchAppinfoArray;
@property(nonatomic,strong)UIButton *insideAppBtn;
@property(nonatomic,strong)UIButton *outsideAppBtn;
@property(nonatomic,strong) UIView *  outsideView ;
@property(nonatomic,strong) UIView *  insideView ;
@property(nonatomic,strong)UIView *statusBar;
@property(nonatomic,strong) NSArray *mTempArray;
@property(nonatomic,strong)UIView *searchView;
@property(nonatomic,strong)AppInfoModel * selectAppInfoModel;
@property(nonatomic,assign)NSInteger selectRow;
@property(nonatomic,weak) AppDetailController *appDetailVC ;
@property(nonatomic,strong)UIView * alertView;
@property(nonatomic,strong) MBProgressHUD * hud;
@end

@implementation AppStoreController

static NSString * const reuseIdentifier = @"Cell";


- (instancetype)init
{
    if (self) {
        //==集合视图控制器====//
        //创建一个collectionViewController需要的流式布局
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        //设置滑动方向
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        float width;
        float height;
        //设置集合视图控制器中cell的大小
        if ([DeviceTypeJudge isPadDeviceType]) {
             width = 75;
            height = 149;
        }else{
            width = 60;
            height = 134 ;
        }
       
        flowLayout.itemSize = CGSizeMake(width, height);
        //设置集合视图控制器的边距
        if ([DeviceTypeJudge isPadDeviceType]) {
            flowLayout.sectionInset = UIEdgeInsetsMake(50, 75, 149,75);
        }else{
            flowLayout.sectionInset = UIEdgeInsetsMake(30, 25, 134,25);
        }
      
        self = [super initWithCollectionViewLayout:flowLayout];
    }
    return self;
}


#pragma mark 设置collectionView的垂直距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if([DeviceTypeJudge isPadDeviceType]){
        return 80;
    }
    return 25;
}
#pragma mark 设置collectionView的水平
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if ([DeviceTypeJudge isPadDeviceType]) {
         return 50 ;
    }
    return 20;
}
#pragma mark 加载网络数据
-(void)loadAppInfoList:(BOOL)updateAllApp{
   MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.collectionView animated:YES];
    self.hud = hud;
    hud.color = [UIColor grayColor];//这儿表示无背景
    //显示的文字
    hud.labelText = @"数据加载中......";
    hud.backgroundColor = [UIColor whiteColor];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    NSString * url = [ApiSupport getAppStoreList];
    if (self.insideAppBtn.selected || updateAllApp) {
        //获得内部应用
        [params setValue:@"2" forKey:@"type"];
        [params setValue:@"1" forKey:@"appType"];
        NSString *insideEncode = [HttpUtil buildUrl:url WithParams:params];
        ASIHTTPRequest *insideEequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:insideEncode]];
        insideEequest.tag = 999;
        //设置网络请求的延时为10秒钟
        insideEequest.timeOutSeconds = 10;
        //设置代理
        insideEequest.delegate=self;
        [insideEequest startAsynchronous];
    }
    if (self.outsideAppBtn.selected || updateAllApp){
        //获得外部应用
        [params setValue:@"2" forKey:@"type"];
        [params setValue:@"2" forKey:@"appType"];
        NSString *encode = [HttpUtil buildUrl:url WithParams:params];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:encode]];
        request.tag = 998;
        //设置网络请求的延时为10秒钟
        request.timeOutSeconds = 10;
        //设置代理
        request.delegate=self;
        [request startAsynchronous];
    }
    
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.userInteractionEnabled = YES;
//    userInterfaceEnabled = YES;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(skinSwitchHandler) name:@"skinswitch" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appHasGoneInForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshProgress) userInfo:nil repeats:YES];
    self.navigationItem.title = nil;
    [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    self.collectionView.backgroundColor = [Utils UIColorFromHex:0xffffff];
    [self.collectionView setY:120];
    [self setStatusBarBackgroundColor:[Utils colorWithKey:@"mainBgColor"]];
    [self addSearchView];
    [self loadAppInfoList:false];
}
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    self.statusBar = statusBar;
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}


//接收到服务器返回的数据时调用
-(void)requestFinished:(ASIHTTPRequest *)request{
    if (request.tag == 999) {
        NSError * error;
        NSArray * insideAppInfoArray  = [NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:&error];
        if (error) {
            NSLog(@"%@",error);
        }
        self.insideAppinfoArray = [AppInfoModel appInfoArrayWithArray:insideAppInfoArray];
    }else{
        NSArray * outsideAppInfoArray  = [NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:nil];
        self.outsideAppinfoArray = [AppInfoModel appInfoArrayWithArray:outsideAppInfoArray];
    }
    
    if (self.insideAppBtn.selected) {
        self.mTempArray = self.insideAppinfoArray;
    }else{
        self.mTempArray = self.outsideAppinfoArray;
    }
    if (self.selectAppInfoModel && self.appDetailVC ) {
        self.selectAppInfoModel = self.mTempArray[self.selectRow];
        [self setBtnState];
    }
   [self.hud hide:YES afterDelay:0];
    [self.collectionView reloadData];
    [self addNoDataImg];
  
}
-(void)addNoDataImg{
    if (self.mTempArray.count == 0) {
        [self.collectionView addSubview:self.alertView];
    }else{
        for (UIView * view in self.collectionView.subviews) {
            if ([view isEqual:self.alertView]) {
                [self.alertView removeFromSuperview];
                break;
            }
        }
    }
}


#pragma mark 添加搜索按钮
-(void)addSearchView{
    UIView * searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 20,self.view.bounds.size.width, 80)];
    searchView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.searchView = searchView;
    [self.view addSubview:searchView];
    
    UITextField * searchtextFiled = [[UITextField alloc]init];
    searchtextFiled.delegate = self;
    self.searchtextFiled = searchtextFiled;
    UIView * leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 45, 47)];
    leftView.backgroundColor = [Utils UIColorFromHex:0xffffff];
    
    UIButton * searchBtn = [[UIButton alloc]init];
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"search_img"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(20);
        make.centerY.mas_equalTo(leftView);
        make.left.mas_equalTo(leftView.mas_left).offset(16);
        make.height.mas_equalTo(20);
    }];
    
    searchtextFiled.attributedPlaceholder = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"str_search", "搜索") attributes:@{NSForegroundColorAttributeName:[Utils UIColorFromHex:0xbbbbbb],NSFontAttributeName:[UIFont systemFontOfSize:17]}];
    [searchtextFiled setFont:[UIFont systemFontOfSize:17]];
    searchtextFiled.layer.cornerRadius = 23;
    searchtextFiled.layer.masksToBounds = YES;
    searchtextFiled.leftView = leftView;
    searchtextFiled.leftViewMode =  UITextFieldViewModeAlways;
    searchtextFiled.backgroundColor = [Utils UIColorFromHex:0xffffff];
    [searchView addSubview:searchtextFiled];
    [searchtextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(330 * KWidthScale);
        make.centerX.mas_equalTo(searchView);
        make.centerY.mas_equalTo(searchView);
        make.height.mas_equalTo(47);
     }];
    UIView * changeView = [[UIView alloc]initWithFrame:CGRectMake(0, 100, self.view.bounds.size.height, 59)];
    changeView.backgroundColor = [Utils UIColorFromHex:0xf4f4f4];
    [self.view addSubview:changeView];
    
    UIButton *insideAppBtn = [[UIButton alloc]init];
    self.insideAppBtn = insideAppBtn;
    [insideAppBtn setTitle:NSLocalizedString(@"str_insideApp", "企业应用") forState:UIControlStateNormal];
     [changeView addSubview:insideAppBtn];
    insideAppBtn.backgroundColor = [Utils UIColorFromHex:0xffffff];
    [insideAppBtn setTitleColor:[Utils colorWithKey:@"mainBgColor"] forState:UIControlStateSelected];
    [insideAppBtn setTitleColor:[Utils UIColorFromHex:0x888888] forState:UIControlStateNormal];
    [insideAppBtn setSelected:YES];
    [insideAppBtn addTarget:self action:@selector(insideAppBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [insideAppBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(changeView.mas_left);
        make.width.mas_equalTo(self.view.bounds.size.width/2);
        make.bottom.mas_equalTo(changeView.mas_bottom);
        make.top.mas_equalTo(changeView.mas_top).offset(8);
    }];
     UIView *  insideView = [[UIView alloc]init];
    self.insideView = insideView;
    insideView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    [changeView addSubview:insideView];
    [insideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(4);
        make.bottom.mas_equalTo(changeView.mas_bottom);
        make.centerX.mas_equalTo(insideAppBtn);
    }];
    
    UIButton *outsideAppBtn = [[UIButton alloc]init];
    self.outsideAppBtn = outsideAppBtn;
    [outsideAppBtn setTitle:NSLocalizedString(@"str_outsideApp", "公有应用") forState:UIControlStateNormal];
    [changeView addSubview:outsideAppBtn];
    outsideAppBtn.backgroundColor = [Utils UIColorFromHex:0xffffff];
    [outsideAppBtn setTitleColor:[Utils colorWithKey:@"mainBgColor"] forState:UIControlStateSelected];
    [outsideAppBtn setTitleColor:[Utils UIColorFromHex:0x888888] forState:UIControlStateNormal];
    [outsideAppBtn setSelected:NO];
    [outsideAppBtn addTarget:self action:@selector(outsideAppBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [outsideAppBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(insideAppBtn.mas_right);
        make.width.mas_equalTo(self.view.bounds.size.width/2);
        make.bottom.mas_equalTo(changeView.mas_bottom);
        make.top.mas_equalTo(changeView.mas_top).offset(8);
    }];
    UIView *  outsideView = [[UIView alloc]init];
    self.outsideView = outsideView;
    outsideView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    [changeView addSubview:outsideView];
    [outsideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(4);
        make.bottom.mas_equalTo(changeView.mas_bottom);
        make.centerX.mas_equalTo(outsideAppBtn);
    }];
    self.outsideView.hidden = YES;
    
    UIView * lineView = [[UIView alloc]init];
    lineView.backgroundColor = [Utils UIColorFromHex:0xe4e4e4];
    [changeView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(changeView);
        make.right.mas_equalTo(changeView);
        make.bottom.mas_equalTo(changeView);
        make.height.mas_equalTo(1);
    }];
}

#pragma mark 企业级应用按钮的点击事件
-(void)insideAppBtnClick:(UIButton *)btn{
    if (btn.selected) {
        return;
    }
    [self.searchAppinfoArray removeAllObjects];
    btn.selected = !btn.selected;
    self.outsideAppBtn.selected = !btn.selected;
    self.outsideView.hidden = YES;
    self.insideView.hidden = NO;
    self.mTempArray = self.insideAppinfoArray;
    [self.collectionView reloadData];
    [self addNoDataImg];
}
#pragma mark 公有级应用按钮的点击事件
-(void)outsideAppBtnClick:(UIButton *)btn{
    if (btn.selected) {
        return;
    }
    [self.searchAppinfoArray removeAllObjects];
    btn.selected = !btn.selected;
    self.insideAppBtn.selected = !btn.selected;
    self.outsideView.hidden = NO;
    self.insideView.hidden = YES;
    if (self.outsideAppinfoArray.count == 0) {
        [self loadAppInfoList:false];
        return;
    }
    self.mTempArray = self.outsideAppinfoArray;
    [self.collectionView reloadData];
//     [self addNoDataImg];
}


//searchBtn的点击事件
-(void)searchBtnClick{
    self.searchAppinfoArray = [NSMutableArray array];
    if (self.searchtextFiled.text == nil || self.searchtextFiled.text.length == 0){
        return;
    }
    NSArray * tempArrat = [NSArray array];
    if (self.insideAppBtn.selected) {
        tempArrat = self.insideAppinfoArray;
    }else{
        tempArrat = self.outsideAppinfoArray;
    }
    for (AppInfoModel * model  in tempArrat) {
        if ([[model.name lowercaseString] containsString:[self.searchtextFiled.text lowercaseString]] ||[[model.name lowercaseString] isEqualToString:[self.searchtextFiled.text lowercaseString]]) {
            [self.searchAppinfoArray addObject:model];
        }
    }
    self.mTempArray = self.searchAppinfoArray;
    [self.collectionView reloadData];
     [self addNoDataImg];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.mTempArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.appInfo = self.mTempArray[indexPath.row];
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    AppDetailController *appDetailVC = [[AppDetailController alloc]init];
    self.appDetailVC = appDetailVC;
    self.selectAppInfoModel = self.mTempArray[indexPath.row];
    self.appDetailVC.model = self.selectAppInfoModel;
    self.selectRow = indexPath.row;
    [self.navigationController pushViewController:self.appDetailVC animated:YES];
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    [self searchBtnClick];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.text == nil || textField.text.length == 0) {
        [self.searchAppinfoArray removeAllObjects];
        if (self.insideAppBtn.selected) {
            self.mTempArray = self.insideAppinfoArray;
        }else{
            self.mTempArray = self.outsideAppinfoArray;
        }
        [self.collectionView reloadData];
         [self addNoDataImg];
    }else{
        [self searchBtnClick];
    }
}

#pragma mark 换肤的处理
- (void)skinSwitchHandler{
    [self.collectionView reloadData];
     [self addNoDataImg];
    self.searchView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.statusBar.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.view.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.insideView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.outsideView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    [self.insideAppBtn setTitleColor:[Utils colorWithKey:@"mainBgColor"] forState:UIControlStateSelected];
    [self.outsideAppBtn setTitleColor:[Utils colorWithKey:@"mainBgColor"] forState:UIControlStateSelected];
}
#pragma mark 应用进入前台的处理事件
- (void)appHasGoneInForeground:(NSNotification *)notification{
    self.mTempArray = nil;
    [self loadAppInfoList:true];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"deskupdate" object:self.insideAppinfoArray];
}
-(void)refreshProgress{
    
    [self updateInstallList];
}
#pragma mark 更新app的状态
-(void)updateInstallList{
    
    void *lib = dlopen("/System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices", RTLD_LAZY);
    
    if (lib)
    {
        Class LSApplicationWorkspace = NSClassFromString(@"LSApplicationWorkspace");
        id AAURLConfiguration1 = [LSApplicationWorkspace defaultWorkspace];
        
        if (AAURLConfiguration1)
        {
            id arrApp = [AAURLConfiguration1 allApplications];
            
            for (int i=0; i<[arrApp count]; i++) {
                
                LSApplicationProxy *LSApplicationProxy = [arrApp objectAtIndex:i];
                NSString* bundleId =[LSApplicationProxy applicationIdentifier];
                NSProgress *progress = (NSProgress *)[LSApplicationProxy installProgress];
                AppInfoModel *model = [self getAppInfoModel:bundleId];
                if ([model.appState isEqualToString:@"安装中"] && progress == nil) {
                    model.appState = @"打开";
                    if(self.appDetailVC){
                        [self setBtnState];
                    }
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"deskupdate" object:self.insideAppinfoArray];
                    [self.collectionView reloadData];
                     [self addNoDataImg];
                }
                if (model) {
                    if (progress) {
                        if (![model.appState isEqualToString:@"安装中"]) {
                            NSUInteger row = [self.mTempArray indexOfObject:model];
                            NSIndexPath *index = [NSIndexPath indexPathForRow:row inSection:0];
                            NSArray *arr = [NSArray arrayWithObject:index];
                            model.progress = [NSString stringWithFormat:@"%lld%%",progress.completedUnitCount];
                            model.appState =@"安装中";
                            [self setBtnState];
                            [self.collectionView reloadItemsAtIndexPaths:arr];
                        }
                    }
                }
                
            }
        }
        
        if (lib) dlclose(lib);
    }

}

- (AppInfoModel *)getAppInfoModel:(NSString *)packageName{
    if([packageName containsString:@".ios8fix"]){
        NSRange range = [packageName rangeOfString:@".ios8fix"];
        packageName = [packageName substringToIndex:range.location];
    }
    for (AppInfoModel *model in self.mTempArray) {
        if ([model.packageName isEqualToString:packageName]) {
            return model;
        }
    }
    return nil;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark 状态按钮的设置
-(void)setBtnState{
    //状态按钮的设置
    if ([self.selectAppInfoModel.appState isEqualToString:@"打开"]) {
        [self.appDetailVC.stateBtn setBackgroundImage:[Utils imageWithKey:@"state_open"] forState:UIControlStateNormal];
        [self.appDetailVC.stateBtn setTitle:@"打开" forState:UIControlStateNormal];
        [self.appDetailVC.stateBtn setTitleColor:[Utils UIColorFromHex:0x26365a] forState:UIControlStateNormal];
    }else if ([self.selectAppInfoModel.appState isEqualToString:@"更新"]){
        [self.appDetailVC.stateBtn setBackgroundImage:[UIImage imageNamed:@"state_update"] forState:UIControlStateNormal];
        [self.appDetailVC.stateBtn setTitle:@"更新" forState:UIControlStateNormal];
    }else if([self.selectAppInfoModel.appState isEqualToString:@"安装"]){
        [self.appDetailVC.stateBtn setBackgroundImage:[Utils imageWithKey:@"state_install"] forState:UIControlStateNormal];
        [self.appDetailVC.stateBtn setTitle:@"安装" forState:UIControlStateNormal];
    }else{
        [self.appDetailVC.stateBtn setBackgroundImage:[Utils imageWithKey:@"state_install"] forState:UIControlStateNormal];
        [self.appDetailVC.stateBtn setTitle:self.selectAppInfoModel.appState forState:UIControlStateNormal];
    }
    
}

- (UIView *)alertView{
    if (_alertView == nil) {
        _alertView  = [[UIView alloc]init];
        _alertView.backgroundColor = [UIColor whiteColor];
        _alertView.frame = self.collectionView.bounds;
        UIImageView * noDataImage = [[UIImageView alloc]init];
        noDataImage.image = [Utils imageWithKey:@"noData_img"];
        [_alertView addSubview:noDataImage];
        if ([DeviceTypeJudge isPadDeviceType]) {
            [noDataImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(_alertView);
                make.top.mas_equalTo(_alertView.mas_top).offset(128);
                make.width.mas_equalTo(125);
                make.height.mas_equalTo(135);
            }];
        }else{
            [noDataImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(_alertView);
                make.top.mas_equalTo(_alertView.mas_top).offset(282);
                make.width.mas_equalTo(164);
                make.height.mas_equalTo(178);
            }];
        }
       
        
    }
    return _alertView;
}


@end
